package com.homework.ch11;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Test0210_CharsetConvertion {

    public static void main(String[] args) {
        String srcEncoding = "GBK";// 源文件编码格式
        String distEncoding = "UTF-8";// 要转换的编码格式
        String dirPath = "D:/test";// 目录路径
        String fileName = "source.txt";// 源文件名
        String distFileName = "target_utf8.txt"; // 目标文件名（可自定义）
        File dir = new File(dirPath);// 创建目录对象
        File source = new File(dir, fileName);// 创建源文件对象
        File target = new File(dir, distFileName); // 目标文件对象

        InputStreamReader isr = null;
        OutputStreamWriter osw = null;
        try {
            // 1. 确保目录存在
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 2. 以GBK编码读取源文件
            isr = new InputStreamReader(new FileInputStream(source), srcEncoding);
            // 3. 以UTF-8编码写入目标文件
            osw = new OutputStreamWriter(new FileOutputStream(target), distEncoding);

            // 4. 逐字符读取并写入，完成编码转换
            int c;
            while ((c = isr.read()) != -1) {
                osw.write(c);
            }
            System.out.println("文件编码从" + srcEncoding + "转换为" + distEncoding + "成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭流释放资源
            try {
                if (isr != null) isr.close();
                if (osw != null) osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}